﻿using UnityEngine;
using System.Collections;

namespace play {
	public class Bomb : MonoBehaviour {
		// Bullet传入的参数
		public int direction;
		public GameObject tank;
		public bool isFromPlayer;

		float speed = 10f;
		bool isFlying = true;
		float bombDelay = 0.25f;

		AudioSource audioSource;
		Animator anim;
		GameObject target;
		Config cfg;

		bool dontCheck = false;

		// fix 爆炸后残留bug
		Vector3 lastPos = Vector3.zero;
		float stopTime = 0;


		// Use this for initialization
		void Start () {
			audioSource = GetComponent<AudioSource> ();
			audioSource.clip = Resources.Load("mp3/bomb") as AudioClip;
			anim = GetComponent<Animator> ();
			anim.StopPlayback ();

			cfg = new Config ();
		}
		
		// Update is called once per frame
		void Update () {
			Vector3 pos = transform.position;
			if (lastPos.x == 0 && lastPos.y == 0 && lastPos.z == 0) {
				lastPos = pos;
			} else {
				if (pos.x == lastPos.x && pos.y == lastPos.y && pos.z == lastPos.z) {
					if (stopTime - 0 < 1e-10) {
						stopTime = Time.time;
					}
					else {
						if (Time.time - stopTime >= 0.9) {
							Network.Destroy(gameObject);
							stopTime = 0;
							lastPos = Vector3.zero;
						}
					}
				}
				else {
					lastPos = pos;
					stopTime = 0;
				}
			}
			// 默认向上
			Vector3 nextPos = new Vector3(pos.x, pos.y + Time.deltaTime * speed, pos.z);

			if (direction == Common.UP) {
				// 上
				nextPos = new Vector3(pos.x, pos.y + Time.deltaTime * speed, pos.z);
			}
			else if (direction == Common.DOWN) {
				// 下
				nextPos = new Vector3(pos.x, pos.y - Time.deltaTime * speed, pos.z);
			}
			else if (direction == Common.LEFT) {
				// 左
				nextPos = new Vector3(pos.x - Time.deltaTime * speed, pos.y, pos.z);
			}
			else if (direction == Common.RIGHT) {
				// 右
				nextPos = new Vector3(pos.x + Time.deltaTime * speed, pos.y, pos.z);
			}

			if (isFlying) {
				transform.position = nextPos;
			}
		}

		void OnTriggerEnter2D(Collider2D c) {
			target = c.collider2D.gameObject;

// print("撞到东西了");
			// 撞到自己穿过去
			if (target.Equals (tank)) {
				return;
			}
			string objName = Common.getObjName (target);
print (transform.name);

			// 炮弹穿不过去
			if (!cfg.canBulletPass(objName)) {
				BoxCollider2D bc = transform.GetComponent<BoxCollider2D> ();
				if (direction == Common.LEFT || direction == Common.RIGHT) {
					bc.size = new Vector2 (0.9f, 1.5f);
				}
				else if (direction == Common.UP || direction == Common.DOWN) {
					bc.size = new Vector2 (1.5f, 0.9f);
				}
				// AI子弹穿过AI
				if (!isFromPlayer && "TANK_AI".Equals(target.tag)) {
					return;
				}

				// 停止飞行
				isFlying = false;
				// 爆炸声音
				if (target.tag.StartsWith("TANK") || "BASE".Equals(target.tag)) {
					audioSource.Play ();
					bombDelay += 0.3f;
				}
				// 子弹消失
				SpriteRenderer sr = transform.GetComponent<SpriteRenderer> ();
				sr.sprite = null;
				// 爆炸动画
				anim.Play ("bomb");
// print(tank);
				try {
					if(isFromPlayer){
// print("bullet bomb");
						tank.transform.GetComponent<PlayerState>().readyToFire = true;
					}
					else{
						tank.transform.GetComponent<AIState>().readyToFire = true;
					}
				}
				catch(MissingReferenceException ex) {
					// print("我们的装甲被击穿 ");
				}



				if (cfg.canBulletDestroy(objName)) {
					// 销毁自身
					GameObject.Destroy (transform.gameObject, bombDelay);

					// AI的子弹 && 打到了玩家
					if (!isFromPlayer && target.tag.StartsWith("TANK_PLAYER")) {

						// 有无敌
						if (target.transform.GetComponent<PlayerState>().isImmune) {
//print ("无敌时间，攻击无效");
							return;
						}
					}

					// 销毁撞到的物体
					GameObject.Destroy (target, bombDelay);

					// 玩家死亡（AI子弹碰到玩家）
					if (!isFromPlayer && target.tag.StartsWith("TANK_PLAYER")) {
						// 正在等待复活，不能再死了
						if (dontCheck) {
							return;
						}

						target.transform.GetComponent<PlayerState>().isAlive = false;

						// 根据关卡复活次数判断fail
						Main.life--;
//print ("复活次数-1");
						// 复活
						if (Main.life >= 0) {
							GameObject.FindGameObjectWithTag("MainCamera").transform.GetComponent<Main>().rebornAfterSec(2);	// 2s后复活
							dontCheck = true;
						}
						// 失败
						else {
print ("life = 0, game over");
							// gameover 页面
							GameObject.FindGameObjectWithTag("MainCamera").transform.GetComponent<Main>().gameoverAfterSec(2);
						}
					}
				}
				else {
					// 销毁自身
					GameObject.Destroy (transform.gameObject, bombDelay);
				}
			}
		}
	}
}